package m.member.order.util;

import m.member.manage.service.AppSettingService;
import m.member.manage.service.LevelUpSetService;
import m.member.manage.service.MemberInfoService;
import m.member.manage.service.MoneyRecordService;
import m.member.order.model.MemberRecharge;
import m.member.order.model.OrderInfo;
import m.member.order.service.MemberRechargeService;
import m.member.order.service.OrderInfoService;
import m.system.RuntimeData;
import m.system.util.NumberUtil;

public class MoneyRecordUtil {
    /**
     * 添加充值记录
     */
    public static void addRecharge(MemberRecharge recharge) throws Exception {
        String busiOid=recharge.getOid(),memberOid=recharge.getMember().getOid();
        Double realMoney=recharge.getPayAmount(),giveMoney=recharge.getGiveAmount();
        Integer point=recharge.getGivePoint();
        //添加记录
        RuntimeData.getService(MoneyRecordService.class)
                .add("C", MemberRechargeService.class,busiOid,memberOid,realMoney,giveMoney,point);
        //更新会员数据
        RuntimeData.getService(MemberInfoService.class).updateAmount(memberOid,realMoney,giveMoney,point);
    }
    public static void removeRecharge(MemberRecharge recharge) throws Exception {
        String busiOid=recharge.getOid(),memberOid=recharge.getMember().getOid();
        Double realMoney=recharge.getPayAmount(),giveMoney=recharge.getGiveAmount();
        Integer point=recharge.getGivePoint();
        //移除记录
        RuntimeData.getService(MoneyRecordService.class).remove(MemberRechargeService.class,busiOid);
        //更新会员数据
        RuntimeData.getService(MemberInfoService.class).updateAmount(memberOid,-realMoney,-giveMoney,-point);
    }
    /**
     * 添加订单记录
     */
    public static void addOrder(OrderInfo order) throws Exception {
        String busiOid=order.getOid(),memberOid=order.getMember().getOid();
        Double realMoney=order.getPayRealMoney(),giveMoney=order.getPayGiveMoney();
        int pointRate=RuntimeData.getService(AppSettingService.class).getPointRate(order.getInputDate());
        int point=NumberUtil.floor((realMoney+giveMoney)*pointRate/100).intValue();
        //添加记录
        RuntimeData.getService(MoneyRecordService.class)
                .add("B", OrderInfoService.class,busiOid,memberOid,-realMoney,-giveMoney,point);
        if("0".equals(order.getPayType())) {
            //更新冻结金额
            RuntimeData.getService(MemberInfoService.class).updateFreeze(order.getMember().getOid(), -order.getPayAmount());
            //更新会员数据
            RuntimeData.getService(MemberInfoService.class).updateAmount(memberOid, -realMoney, -giveMoney, point);
        }else{
            //更新会员数据
            RuntimeData.getService(MemberInfoService.class).updateAmount(memberOid, 0d, 0d, point);
        }
        RuntimeData.getService(MemberInfoService.class).addOrder(memberOid,NumberUtil.round(realMoney+giveMoney));
        //会员自动升级
        RuntimeData.getService(LevelUpSetService.class).autoUpSet(memberOid);
    }
}
